import { Application } from 'egg'
import { Schema } from 'mongoose'
import * as AutoIncrementFactory from 'mongoose-sequence'

export interface UserProps {
  type?: 'email' | 'cellphone' | 'oauth'
  /** 用户名 */
  username: string
  /** 用户密码 */
  password?: string
  /** 用户邮箱 */
  email?: string
  /** 用户昵称 */
  nickname?: string
  /** 用户头像 */
  picture?: string
  /** 用户手机号码 */
  phoneNumber?: string
  createdAt: Date
  updatedAt: Date
  provider?: 'gitee'
  oauthID?: string
  autoIncrementId: number
}

export default (app: Application) => {
  const AutoIncrement = AutoIncrementFactory(app.mongoose)
  const UserSchema = new Schema<UserProps>(
    {
      username: { type: String, unique: true, required: true },
      password: { type: String },
      email: { type: String },
      nickname: { type: String },
      picture: { type: String },
      phoneNumber: { type: String },
      type: { type: String, default: 'email' },
      provider: { type: String },
      oauthID: { type: String },
    },
    {
      timestamps: true,
      toJSON: {
        transform: (_doc, ret) => {
          delete ret.password
          delete ret.__v
          delete ret._id
        },
      },
    },
  )
  UserSchema.plugin(AutoIncrement, {
    inc_field: 'autoIncrementId',
    id: 'user_schema_seq',
  })
  return app.mongoose.model<UserProps>('User', UserSchema)
}
